//
//  RJOutDetailTableVC.m
//  AirQuality
//
//  Created by Po on 15/7/3.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJOutDetailTableVC.h"
#import "RJCheckDataBottomTableModel.h"
#import "RJCheckDataFitCell.h"


@interface RJOutDetailTableVC () <RJCheckDataFitCellDelegate>

@property (retain, nonatomic) UIView * sectionView;                      //表头
@property (retain, nonatomic) UIImageView * selectImage;                 //选中背景
@property (retain, nonatomic) RJCheckDataCellButton * currentButton;     //当前选中按钮

@property (retain, nonatomic) RJCheckDataBottomTableModel * model;       //数据
@property (retain, nonatomic) NSMutableArray * problemTimes;             //问题事件

- (void)initData;
- (void)initInterface;
@end

@implementation RJOutDetailTableVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        _onlyShow = NO;
        _near24Hour = NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    [self initInterface];
}

#pragma mark - user-defined initialization function
- (void)initData
{
    _showProblem = NO;
    _model = [[RJCheckDataBottomTableModel alloc] init];
    _model.startTime = 0;
    _problemTimes = [[NSMutableArray alloc] init];
}

- (void)initInterface
{
    //self init
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    //all init
    [self.view addSubview:[self getSelectImage]];
}

- (UIImageView *)getSelectImage
{
    if (!_selectImage) {
        _selectImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth / (_model.cellKeys.count + 1), 44)];
        [_selectImage setImage:[UIImage imageNamed:@"dataSelectHighLight"]];
        [_selectImage setHidden:YES];
    }
    return _selectImage;
}

- (void)setNear24Hour:(BOOL)near24Hour
{
    _near24Hour = near24Hour;
    if (_near24Hour) {
        _model.startTime = [[RJTools getTimeWithFormat:@"hh"] integerValue];
    }
}
#pragma mark - function
- (CGRect)getDetailBoxRect:(CGRect)rect
{
    CGFloat length = rect.origin.y + rect.size.height;
    if (length > ScreenHeight) {
        //当前Y减去按钮高度为上方
        rect.origin.y -= (rect.size.height + 40);
    }
    return rect;
}

- (void)setData:(NSArray *)data time:(NSUInteger)time cellKeys:(NSArray *)cellKeys
{
    _model.data = [NSMutableArray arrayWithArray:data];
    _model.time = time;
    _model.cellKeys = [NSArray arrayWithArray:cellKeys];
    [self.tableView reloadData];
}

- (void)setCellKeys:(NSArray *)keys
{
    _model.cellKeys = [NSArray arrayWithArray:keys];
    _model.headCellTitles = [RJTools getTrueCellTitleWithKeys:keys];
    CGRect rect = self.tableView.frame;
    self.tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    [[self getSelectImage] removeFromSuperview];
    _selectImage = nil;
    [self.view insertSubview:[self getSelectImage] aboveSubview:self.tableView];
    [self.tableView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"tableBackground"]]];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView reloadData];
}

- (void)showProblem:(BOOL)isShow
{
    if (_showProblem == isShow) {
        return;
    }
    _showProblem = isShow;
    [_problemTimes removeAllObjects];
    
    if (_showProblem) {
        NSMutableArray * probleamKeys = [NSMutableArray arrayWithArray:@[@"pm2_5",@"pm10",@"o3",@"so2",@"no2",@"co"]];
        NSMutableArray * tempKeys = [NSMutableArray arrayWithArray:probleamKeys];
        for (NSUInteger i = 0; i < _model.data.count; i ++) {
            NSDictionary * dic = _model.data[i];
            BOOL isCheckTime = NO;
            for (NSUInteger j = 0; j < probleamKeys.count; j ++) {
                NSString * markKey = [NSString stringWithFormat:@"%@_mark",probleamKeys[j]];
                NSString * mark = dic[markKey];
                //判断是否为无效数据
                if ([mark isEqualToString:@""]) {
                    continue;
                } else if (([mark rangeOfString:@"RM"].location != NSNotFound) || ([mark rangeOfString:@"H"].location != NSNotFound) ) {
                    if ([mark rangeOfString:@"HSp"].location != NSNotFound) {
                        continue;
                    } else {
                        
                        if (![tempKeys[j] isEqualToString:@""]) {
                            tempKeys[j] = @"";
                        }
                        //是否已经保留了当前事件
                        if (!isCheckTime) {
                            [_problemTimes addObject:@(i)];
                            isCheckTime = YES;
                        }
                    }
                } else {
                    continue;
                }
            }
        }
        
        //删选出问题Key
        for (NSString * key in tempKeys) {
            if ([probleamKeys indexOfObject:key] != NSNotFound) {
                [probleamKeys removeObject:key];
            }
        }
        
        //        [self setCellKeys:probleamKeys];
    } else {
        [self setCellKeys:@[@"pm2_5",@"pm10",@"o3",@"so2",@"no2",@"co"]];
    }
    
    [self.tableView reloadData];
}

#pragma mark - Table view data source

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_showProblem) {
        return _problemTimes.count;
    }
    
    return 24;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (RJCheckDataFitCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * cellIdent = @"RJCheckDataFitCell";
    RJCheckDataFitCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdent];
    if (!cell) {
        cell = [[RJCheckDataFitCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RJCheckDataFitCell"];
        [cell setButtonNum:_model.cellKeys.count + 1];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.selectedBackgroundView = [[UIView alloc] init];
        [cell setDelegate:self];
    }
    
    [cell setBackgroundColor:(indexPath.row % 2 == 0) ? [UIColor clearColor] : [UIColor colorWithPatternImage:[UIImage imageNamed:@"homeTableCellBack"]]];
    
    //计算时间
    NSInteger time;
    if (_showProblem) {
        time = [_problemTimes[indexPath.row] integerValue];
    } else {
        time = indexPath.row + _model.startTime;
    }
    
    if (++time >= 24) {
        time -= 24;
    }
    
    NSString * timeString = [NSString stringWithFormat:@"%2ld时",time];
    
    [cell.allButtons[0] setTitle:timeString forState:UIControlStateNormal];
    [cell.allButtons[0] setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    NSUInteger arrayCount = _showProblem ? ([_problemTimes[indexPath.row] integerValue]):indexPath.row;
    if (_model.data.count != 0) {
        NSDictionary * dic = _model.data[arrayCount];
        //获取数值按钮
        NSArray * buttons = [cell.allButtons subarrayWithRange:NSMakeRange(1, cell.allButtons.count - 1)];
        //标示按钮（方便后面计算），并设置值
        for (NSUInteger i = 0; i < cell.allButtons.count - 1; i ++) {
            [self setCellButton:buttons[i] dataDic:dic key:_model.cellKeys[i]];
        }
    }
    return cell;
}

- (void)setCellButton:(RJCheckDataCellButton *)button dataDic:(NSDictionary *)dataDic key:(NSString *)key
{
    
    NSString * markString = [dataDic objectForKey:[NSString stringWithFormat:@"%@_mark",key]];
    if (!markString) {
        markString = @"";
    }
    [button setMark:markString];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    if ([key isEqualToString:@"co"] || [key isEqualToString:@"CO"]) {
        NSString * num = [NSString stringWithFormat:@"%.3f",[dataDic[key] floatValue]];
        [button setTitle:num forState:UIControlStateNormal];
        return;
    }
    [button setTitle:GetStringWithNum(dataDic[key]) forState:UIControlStateNormal];
    
}


#pragma mark - RJCheckDataCellDelegate
/**点击对应的数值时*/
- (void)RJCheckDataFitCellDidSelect:(RJCheckDataCellButton *)button cell:(RJCheckDataFitCell *)cell
{

}

@end
